<script setup lang="ts">
import {DevSearchTable} from "devecoui-plus";
import {type PropType, reactive, ref, watch} from "vue";

interface PropsType {
  [key: string]: any
}

interface DataType {
  props?: PropsType;
  explain: {
    [key: string]: {
      type?: string;
      defaultValue?: any;
      explain: string;
      optionalValues?: string;
      link?: string;
    };
  };
  removes?: string[];
  isKebabCase?: boolean;
}

const props = defineProps({
  data: {
    type: Object as PropType<DataType>,
    default: () => ({props: {}, explain: {}})
  },
  type: {
    type: String as PropType<'attribute' | 'event' | 'slot' | 'method'>,
    default: 'attribute'
  }
})

const nameTypeObj = ref({
  attribute: '属性名',
  event: '事件名',
  slot: '插槽名',
  method: '方法名'
})
const columns = reactive([
  {
    label: nameTypeObj.value[props.type],
    prop: 'name',
  },
  {
    label: '说明',
    prop: 'explain',
  },
  {
    label: '类型',
    prop: 'type',
    align: 'center',
    hide: ['slot'].includes(props.type),
  },
  {
    label: '默认值',
    prop: 'value',
    align: 'center',
    hide: props.type !== 'attribute',
  },
  {
    label: '可选值',
    prop: 'optionalValues',
    align: 'center',
    hide: props.type !== 'attribute',
  }
])

interface ListType {
  name: string;
  value: any;
  type: string;
  explain: string;
  optionalValues?: any;
  link?: string;
}

const list = ref<ListType[]>([])

/**
 * 将驼峰命名字符串转换为kebab-case
 * @param str - 需要转换的驼峰字符串
 * @returns 转换后的kebab-case字符串
 */
function camelToKebab(str: string): string {
  return str
      .replace(/([a-z])([A-Z])/g, '$1-$2') // 找到小写字母和大写字母的边界，并添加 -
      .replace(/([A-Z])/g, '$1') // 找到所有的大写字母，并在前面添加 -
      .toLowerCase(); // 将整个字符串转换为小写
}

watch(
    () => props.data,
    (value: DataType) => {
      const arr: ListType[] = [];

      for (const key in value.explain) {
        if (Object.prototype.hasOwnProperty.call(value.explain, key)) {
          if(value?.removes?.includes(key)) continue;
          arr.push({
            name:value?.isKebabCase? camelToKebab(key):key,
            value: value.explain[key]?.defaultValue || '—',
            type: value.explain[key]?.type || '—',
            explain: value.explain[key]?.explain || '—',
            optionalValues: value.explain[key]?.optionalValues || '—',
            link: value.explain[key]?.link,
          });
        }
      }
      list.value = arr;
    },
    {deep: true, immediate: true}
);

</script>

<template>
  <dev-search-table :data="list" :openRequest="false" :columns="columns">
    <template #optionalValues="{item}">
      <a class="a-href" v-if="item.link" :href="item.link" target="_blank">{{ item.optionalValues }}</a>
      <span v-else>{{ item.optionalValues }}</span>
    </template>
  </dev-search-table>
</template>

<style scoped>
.a-href{
  color: var(--dev-g-primary-color);
  text-decoration: none;
}
</style>
